<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\facade\Db;
use think\Request;

class OrderFleet extends Api
{
    protected $with = ['business', 'user_index','script'=>['script_class.script_setting','script_setting_xs','script_setting_nd','script_role'], 'order_member' => ['user_index', 'business', 'virtual_characters']];
    public function lj_index()
    {
        $this->checkLogin();
        if (input('post.limit')) {
            $this->limit = input('post.limit');
        }
        $post = array_filter(input('post.'));
        if(!isset($post['business_id'])) return msgerror('参数缺失');
        $order = $post['order'] ?? 'id desc';
        $Script_model = app('app\api\model\Script');
        //剧本名搜索-高优先级
        if(isset($post['name'])){
            $where = [
                ['business_id','=',$post['business_id']],
                ['name','like','%'.$post['name'].'%']
            ];
            $list = $ScriptScreen_model->where($where)->order($order)->select();
            if(!empty($list) && !empty($list->toArray()))
            {
                $list = $list->toArray();
                $script_ids = [];
                foreach ($list as $k=>$v){
                    $script_ids[] = $v['id'];
                }
                $script_ids = implode(',',$script_ids);
                $where = [
                    ['script_id','in',$script_ids],
                    ['status','=',1]
                ];
                $list = $this->model->with($this->with)->order($order)->where($where)->paginate($this->limit);
                if (!empty($list)) {
                    $list = $list->toArray();
                    foreach($list['data'] as $k=>$v)
                    {
                        if(!empty($v['script']['image'])){
                            $list['data'][$k]['script']['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $v['script']['image'];
                        }
                        $list['data'][$k]['script']['images'] = explode(',',$v['script']['images']);
                        foreach ($list['data'][$k]['script']['images'] as $kk=>$vv)
                        {
                            $list['data'][$k]['script']['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
                        }
                        foreach ($v['script']['script_role'] as $kk=>$vv){
                            if(!empty($vv['image'])){
                                $list['data'][$k]['script']['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
                            }
                        }
                        
                    }
                    urladd($list);
                }
            }
        }
        //发送了筛选数据
        if(isset($post['sx'])){
            $ScriptScreen_model = app('app\api\model\ScriptScreen');
            //查出当前门店下所有剧本ID
            $data = $Script_model->where('business_id','=',$post['business_id'])->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
            }else{
                return datasuccess([]);
            }
            $script_ids = [];
            foreach ($data as $k=>$v){
                $script_ids[] = $v['id'];
            }
            $script_ids = implode(',',$script_ids);
            $post['sx'] = explode(',',$post['sx']);
            $post['sx'] = array_filter($post['sx']);
            $post['sx'] = implode(',',$post['sx']);
            $where = [
                ['script_id','in',$script_ids],
                ['screen_id','in',(string)$post['sx']]
            ];
            //根据所有剧本ID和筛选ID查出符合记录的剧本ID数据
            $order = 'id desc';
            $list = $ScriptScreen_model->where($where)->order($order)->select();
            if (!empty($list)) {
                $list = $list->toArray();
            }else{
                return datasuccess([]);
            }
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['script_id'];
            }
            $ids = array_unique($ids);
            $ids = implode(',',$ids);
            $where = [];
            $where[] = ['id','in',$ids];
            
            //根据筛选ID查出对应的剧本数据
            $list = $Script_model->where('id','in',$ids)->with('script_screen')->select()->toArray();
            foreach ($list as $k=>$v){
                $num = count(explode(',',$post['sx']));
                $mz = 0;
                foreach ($v['script_screen'] as $kk=>$vv){
                    foreach (explode(',',$post['sx']) as $kkk=>$vvv){
                        if($vv['screen_id'] == $vvv){
                            $mz++;
                        }
                    }
                }
                if($mz < $num){
                    unset($list[$k]);
                }
            }
            if(empty($list)){
               return datasuccess();  
            }else{
                $ids = [];
                foreach ($list as $v){
                    $ids[] = $v['id'];
                }
                $ids = implode(',',$ids);
                $where = [
                    ['script_id','in',$ids]    
                ];
            }
            
            $where[] = ['status','=',1];
            //根据剧本ID查询下面所有的车队数据 数据ID数据重新查询符合排序顺序的分页数据
            $list = $this->model->with($this->with)->order($order)->where($where)->paginate($this->limit);
            if (!empty($list)) {
                $list = $list->toArray();
                foreach($list['data'] as $k=>$v)
                {
                    if(!empty($v['script']['image'])){
                        $list['data'][$k]['script']['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $v['script']['image'];
                    }
                    $list['data'][$k]['script']['images'] = explode(',',$v['script']['images']);
                    foreach ($list['data'][$k]['script']['images'] as $kk=>$vv)
                    {
                        $list['data'][$k]['script']['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
                    }
                    foreach ($v['script']['script_role'] as $kk=>$vv){
                        if(!empty($vv['image'])){
                            $list['data'][$k]['script']['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
                        }
                    }
                    
                }
                urladd($list);
            }
            return datasuccess($list);
        }
        $this->where[] = ['business_id','=',$post['business_id']];
        $list = $Script_model->with(['business','script_screen','script_setting_nd','script_setting_xs','script_class.script_setting','script_role'])->order($order)->where($this->where)->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['id'];
            }
            $ids = implode(',',$ids);
            $list = $this->model->where([
                ['status','=',1],
                ['script_id','in',$ids]
            ])->with($this->with)->order('id desc')->paginate($this->limit);
            
            if(!empty($list) && !empty($list->toArray())){
                $list = $list->toArray();
            }
            foreach($list['data'] as $k=>$v)
            {
                $list['data'][$k]['script']['images'] = explode(',',$v['script']['images']);
                foreach ($list['data'][$k]['script']['images'] as $kk=>$vv)
                {
                    $list['data'][$k]['script']['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
                }
                foreach ($v['script']['script_role'] as $kk=>$vv){
                    if(!empty($vv['image'])){
                        $list['data'][$k]['script']['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
                    }
                }
                
            }
            urladd($list);
        }
        return datasuccess($list);
    }
    //用户端-预约详情-退出车队
    public function tc()
    {
        $this->checkLogin();
        $post = param();
        //车队ID
        if(!isset($post['id'])) return msgerror('参数缺失');
        $order_fleet_data = $this->model->where('id',$post['id'])->find();
        if(!empty($order_fleet_data) && !empty($order_fleet_data->toArray())){
            $order_fleet_data = $order_fleet_data->toArray();
            if($order_fleet_data['status'] != 1) return msgerror('只有待发车的车队能够退出车队');
            $OrderMember_model = app('app\api\model\OrderMember');
            $member_data = $OrderMember_model->where([
                ['order_fleet_id','=',$post['id']],
                ['user_index_id','=',$this->userinfo['id']],
                ['user_type','=',1]
            ])->find();
            if(!empty($member_data) && !empty($member_data->toArray())){
                $member_data = $member_data->toArray();
                if($member_data['status'] == 2){
                    return msgerror('你已经退出了车队，不要重复调用接口');
                }
                //退出车队
                $OrderMember_model::update(['id'=>$member_data['id'],'status'=>3]);
                $num = $OrderMember_model->where([
                    ['order_fleet_id','=',$post['id']],
                    ['user_type','=',1],
                    ['status','=',1]
                ])->count('id');
                if($num == 0){
                    //当车队中没有人存在时，进行解散操作
                    $this->model::update(['id'=>$post['id'],'status'=>5]);
                }else{
                    if($member_data['type'] == 1){
                        //退出者是队长，车队还有其他成员的前提下，需要选择其他人成员队长
                        $jc_data = $OrderMember_model->where([
                            ['order_fleet_id','=',$post['id']],
                            ['user_type','=',1],
                            ['status','=',1]
                        ])->order('id asc')->find()->toArray();
                        //继承队长身份
                        $OrderMember_model::update(['id'=>$jc_data['id'],'type'=>1]);
                    }
                }
                return datasuccess([],'退出成功');
            }else{
                return msgerror('你不在车队成员中，退出失败');
            }
        }else{
            return msgerror('车队不存在');
        }
    }
    //用户端-重新加入车队
    public function cx_add()
    {
        $this->checkLogin();
        $post = param();
        //车队ID
        if(!isset($post['id'])) return msgerror('参数缺失');
        $order_fleet_data = $this->model->where('id',$post['id'])->find();
        if(!empty($order_fleet_data) && !empty($order_fleet_data->toArray())){
            $order_fleet_data = $order_fleet_data->toArray();
            if($order_fleet_data['status'] != 1) return msgerror('只有待发车的车队能够重新加入');
            $OrderMember_model = app('app\api\model\OrderMember');
            $member_data = $OrderMember_model->where([
                ['order_fleet_id','=',$post['id']],
                ['user_index_id','=',$this->userinfo['id']],
                ['user_type','=',1]
            ])->find();
            if(!empty($member_data) && !empty($member_data->toArray())){
                $member_data = $member_data->toArray();
                if($member_data['status'] == 3){
                    $OrderMember_model::update(['id'=>$member_data['id'],'status'=>1]);
                    return datasuccess([],'重新加入成功');
                }else{
                    return msgerror('你已在车队中，不需要重新加入');
                }
            }else{
                return msgerror('你不在车队成员中，重新加入失败');
            }
        }else{
            return msgerror('车队不存在');
        }
    }
    //用户端-预约详情-删除预约
    public function scyy()
    {
        $this->checkLogin();
        $post = param();
        if(!isset($post['id'])) return msgerror('参数缺失');
        $order_fleet_data = $this->model->where('id',$post['id'])->find();
        if(!empty($order_fleet_data) && !empty($order_fleet_data->toArray()))
        {
            $order_fleet_data = $order_fleet_data->toArray();
            if($order_fleet_data['status'] == 4 || $order_fleet_data['status'] == 5 || $order_fleet_data['status'] == 1){
                //只有待发车，已完成，已解散的车队可以进行删除预约操作
                $OrderMember_model = app('app\api\model\OrderMember');
                $member_data = $OrderMember_model->where([
                    ['order_fleet_id','=',$post['id']],
                    ['user_index_id','=',$this->userinfo['id']],
                    ['user_type','=',1]
                ])->find();
                if(!empty($member_data) && !empty($member_data->toArray())){
                    $member_data = $member_data->toArray();
                    if($member_data['is_del'] == 1){
                        if($member_data['status'] == 1 && $order_fleet_data['status'] == 1){
                            return msgerror('待发车队伍，只有退出队伍后，才能进行删除预约的操作');
                        }
                        $this->model::update(['id'=>$member_data['id'],'is_del'=>1]);
                        return datasuccess([],'删除预约成功');
                    }else{
                        return msgerror('已经删除预约，不要重复调用接口');
                    }
                }else{
                    return msgerror('你不在车队成员中，删除预约失败');
                }
            }else{
                return msgerror('当前车队状态不能进行删除预约操作');
            }
        }else{
            return msgerror('车队不存在');
        }
    }
    //预约队列-商户端
    public function bus_index()
    {
        $this->businessCheckLogin();
        $post = param();
        if (isset($post['where']) && !empty($post['where']) && is_array($post['where'])) {
            foreach ($post['where'] as $k => $v) {
                if (is_array($v)) {
                    if (isset($v['key']) && isset($v['value'])) {
                        if (isset($v['i'])) {
                            $this->where[] = [$v['key'], $v['i'], $v['value']];
                        } else {
                            $this->where[] = [$v['key'], '=', $v['value']];
                        }
                    }
                } else {
                    $this->where[] = [$k, '=', $v];
                }
            }
        }
        $this->where[] = ['business_id', '=', $this->businessinfo['id']];
        $this->where[] = ['is_del', '=', 2];
        $this->order = $post['order'] ?? $this->order;
        $this->limit = $post['limit'] ?? $this->limit;
        $this->field = $post['field'] ?? $this->field;
        $data = $this->model->where($this->where)->order($this->order)->with($this->with)->field($this->field)->paginate($this->limit)->toArray();
        return datasuccess($data);
    }
    //用户端-立即预约-剧本下的车队列表
    public function script_index()
    {
        $this->checkLogin();
        $post = param();
        //id = 剧本ID
        if(!isset($post['id'])) return msgerror('参数缺失');
        $this->limit = $post['limit'] ?? $this->limit;
        $data = $this->model->where([
            ['script_id','=',$post['id']],
            ['status','=',1]
        ])->with($this->with)->paginate($this->limit);
        return datasuccess($data);
    }
    //用户端-加入该车队
    public function jr_add()
    {
        $this->checkLogin();
        $post = param();
        //车队ID
        if(!isset($post['id'])) return msgerror('参数缺失');
        $data = $this->model->where('id',$post['id'])->find()->toArray();
        if($data['status'] != 1) return msgerror('只有待发车的车队能够加入成员');
        $OrderMember_model = app('app\api\model\OrderMember');
        //判断当前用户是否有加入其它车队，且发车时间和当前车队的发车时间需要间隔大于2小时
        //2小时偏差值时间
        // if($data['departure_time'])
        $time_sx = date('Y-m-d H:i:s' , strtotime($data['departure_time'])+(60*60*2));
        $time_xx = date('Y-m-d H:i:s' , strtotime($data['departure_time'])-(60*60*2));
        $order_id = $OrderMember_model->where([
            ['user_index_id','=',$this->userinfo['id']],
            ['status','=',1],
            ['wc','=',2]
        ])->group('order_fleet_id')->select();
        if(!empty($order_id) && !empty($order_id->toArray()))
        {
            $order_id = $order_id->toArray();
            $ids = [];
            foreach ($order_id as $k=>$v)
            {
                $ids[] = $v['order_fleet_id'];
            }
            //根据加入的成员记录中的所有车队ID，查看所有车队ID中是否有在偏差值范围内的发车时间，如果存在，就不能再加入该车队
            $ids = implode(',',$ids);
            $pc_data = $this->model->where([
                ['id','in',$ids],
                ['departure_time','>=',$time_xx],
                ['departure_time','<=',$time_sx]
            ])->select();
            if(!empty($pc_data) && !empty($pc_data->toArray())) return msgerror('加入失败，你在该车队发车时间的2小时内，你已有其他剧本车队');
        }
        $arr = [
            'order_fleet_id'=>$post['id'],
            'user_index_id'=>$this->userinfo['id'],
            'status'=>1,
            'user_type'=>1,
            'name'=>$this->userinfo['nickname'],
            'tel'=>$this->userinfo['tel'],
            'type'=>2
        ];
        $delete = true;
        if($data['type'] == 1){
            //如果该车队是门店创建的，检查对账是否是虚拟角色，是的话需要顶替虚拟角色成为队长
            $OrderMember_data = $OrderMember_model->where([
                ['order_fleet_id','=',$post['id']],
                ['type','=',1]
            ])->find()->toArray();
            //队长为虚拟人物,更换队长
            if($OrderMember_data['user_type'] == 3){
                $arr['type'] = 1;
                $this->model::destroy($OrderMember_data['id']);
                $delete = false;
            }
        }
        //顶替1个人只会发生一次
        //检查队伍中是否存在虚拟角色，存在的话每加入一个人需要顶替掉一个虚拟角色
        $xn_data = $OrderMember_model->where([['status','=',1],['user_type','=',3]])->find();
        if(!empty($xn_data) && !empty($xn_data->toArray()) && $delete){
            $xn_data = $xn_data->toArray();
            $OrderMember_model::destroy($xn_data['id']);
        }
        //微信订阅消息-加入活动成果
        $app = Factory::miniProgram($this->yh_easy_config);
        if(!empty($this->userinfo['wx_openid'])){
            $dy_data = [
                'template_id' => '8-xXs6zkNZNSe3FefbnMunNFMSiNmrrbXDwoTw1JRZM', // 所需下发的订阅模板id
                'touser' => $this->userinfo['openid'],     // 接收者（用户）的 openid
                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'thing1' => [
                        'value' => $data['script']['name'],
                    ],
                    'time2' => [
                        'value' => $data['arrival_day'].' '.$data['arrival_time'],
                    ],
                    'thing3' => [
                        'value' => $data['business_id']['nickname'],
                    ],
                    'thing4' => [
                        'value' => $data['business_id']['address'],
                    ],
                ],
            ];
            $app->subscribe_message->send($dy_data);
        }
        $OrderMember_model->save($arr);
        //添加完成后，检查人数是否达到发车人数-达成的就修改车队状态，发送通知
        $num = $OrderMember_model->where([
            ['order_fleet_id','=',$post['id']],
            ['status','=',1]
        ])->with('user_index')->select()->toArray();
        $Script_model = app('app\api\model\Script');
        $Script_data = $Script_model->where('id',$data['script_id'])->find()->toArray();
        $arr = [];
        $arr[] = [
            'type'=>1,
            'name'=>'加入车队成功',
            'content'=>'您已成功加入关于"'.$Script_data['name'].'"的车队',
            'user_index_id'=>$this->userinfo['id']
        ];
        $Msg_model = app('app\api\model\Msg');
        if($data['script_num'] <= count($num)){
            $app = Factory::miniProgram($this->sh_easy_config);
            //人数齐了-发车
            $this->model::update(['id'=>$post['id'],'status'=>2]);
            //通知门店，人数已齐-微信订阅消息
            $business_data = app('app\api\model\Business')->where('id',$data['business_id'])->find()->toArray();
            if(!empty($business_data['openid']) && $business_data['dy_num'] > 0){
                $dy_data = [
                    'template_id' => 'cNySmltkoAPrVwdh3SWcKq4MzNzqzIpu9mrZsIsVOl0', // 所需下发的订阅模板id
                    'touser' => $business_data['openid'],     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'thing1' => [
                            'value' => $data['script']['name'],
                        ],
                        'thing2' => [
                            'value' => $data['arrival_day'].' '.$data['arrival_time'],
                        ],
                        'thing3' => [
                            'value' => $business_data['nickname'],
                        ],
                        'thing4' => [
                            'value' => $business_data['address'],
                        ],
                    ],
                ];
                $app->subscribe_message->send($dy_data);
                //减少订阅次数
                app('app\api\model\Business')->where('id',$business_data['id'])->dec('dy_num')->update();
            }
            $app = Factory::miniProgram($this->yh_easy_config);
            //发送消息通知
            //人数齐了通知-微信订阅消息
            foreach ($num as $v){
                //组装站内消息
                $arr[] = [
                    'type'=>1,
                    'name'=>'你所在的车队人数已齐',
                    'content'=>'关于"'.$Script_data['name'].'"剧本的车队人数已齐',
                    'user_index_id'=>$v['user_index_id']
                ];
                //发送微信订阅消息-人数已齐通知
                if(!empty($v['user_index']['wx_openid'])){
                    $dy_data = [
                        'template_id' => 'cNySmltkoAPrVwdh3SWcKq4MzNzqzIpu9mrZsIsVOl0', // 所需下发的订阅模板id
                        'touser' => $v['user_index']['openid'],     // 接收者（用户）的 openid
                        'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                        'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                            'thing1' => [
                                'value' => $data['script']['name'],
                            ],
                            'time2' => [
                                'value' => $data['arrival_day'].' '.$data['arrival_time'],
                            ],
                            'thing3' => [
                                'value' => $data['business_id']['nickname'],
                            ],
                            'thing4' => [
                                'value' => $data['business_id']['address'],
                            ],
                        ],
                    ];
                    $app->subscribe_message->send($dy_data);
                }

            }
        }
        //添加预约量记录
        $ScriptYyLog_model = app('app\admin\model\ScriptYyLog');
        $ScriptYyLog_model->save([
            'business_id'=>$data['business_id'],
            'script_id'=>$data['script_id']
        ]);
        $Msg_model->saveAll($arr);
        return datasuccess();
    }
    //组建车队-商户端
    public function bus_add()
    {
        $this->businessCheckLogin();
        $res = $this->add(1);
        return $res;
    }

    //组建车队-用户端
    public function user_add()
    {
        $this->checkLogin();
        $res = $this->add(2);
        return $res;
    }

    //组建车队-数据添加
    public function add($type = 1)
    {
        $post = array_filter(input('post.'));
        if (!empty($post)) {
            if (!isset($post['script_id']) || !isset($post['arrival_day']) || !isset($post['arrival_status']) || !isset($post['arrival_time'])) return msgerror('参数缺失');
            if ($type == 2) {
                //用户
                $post['type'] = 2;
                $post['user_index_id'] = $this->userinfo['id'];
                //用户组建的车队，需要判断组建车队的发车时间2小时内是否已经有加入了的车队了，如果存在就不能创建新的车队
                //2小时偏差值时间
                $time_sx = date('Y-m-d H:i:s' , strtotime($post['arrival_day'].' '.$post['arrival_time'])+(60*60*2));
                $time_xx = date('Y-m-d H:i:s' , strtotime($post['arrival_day'].' '.$post['arrival_time'])-(60*60*2));
                $OrderMember_model = app('app\api\model\OrderMember');
                $order_id = $OrderMember_model->where([
                    ['user_index_id','=',$this->userinfo['id']],
                    ['status','=',1],
                    ['wc','=',2]
                ])->group('order_fleet_id')->select();
                if(!empty($order_id) && !empty($order_id->toArray()))
                {
                    $order_id = $order_id->toArray();
                    $ids = [];
                    foreach ($order_id as $k=>$v)
                    {
                        $ids[] = $v['order_fleet_id'];
                    }
                    //根据加入的成员记录中的所有车队ID，查看所有车队ID中是否有在偏差值范围内的发车时间，如果存在，就不能在创建车队了
                    $ids = implode(',',$ids);
                    $pc_data = $this->model->where([
                        ['id','in',$ids],
                        ['departure_time','>=',$time_xx],
                        ['departure_time','<=',$time_sx]
                    ])->select();
                    if(!empty($pc_data) && !empty($pc_data->toArray())) return msgerror('创建失败，该到店时间的2小时内，你已有其他剧本车队');
                }
            } else {
                //门店
                $post['business_id'] = $this->businessinfo['id'];
                $post['type'] = 1;
//                $post['business_user_id'] = $this->businessinfo['id'];
            }
            $Script_model = app('app\api\model\Script');
            $script_data = $Script_model->where('id', $post['script_id'])->with([
                'business', 'script_screen',
                'script_setting_nd', 'script_setting_xs',
                'script_class.script_setting', 'script_role'
            ])->find()->toArray();
            //完善车队信息
            $post['status'] = 1;
            $post['departure_time'] = $post['arrival_day'] . ' ' . $post['arrival_time'] . ':00';
            $post['script_name'] = $script_data['name'];
            $post['script_f_num'] = $script_data['sex_f'];
            $post['script_m_num'] = $script_data['sex_m'];
            $post['script_num'] = ($script_data['sex_m']*1 + $script_data['sex_f']*1);
            $post['script_difficulty'] = $script_data['script_setting_nd']['name'];
            $post['script_price'] = $script_data['price'];
            $post['script_xs'] = $script_data['script_setting_xs']['name'];
            $post['script_time'] = $script_data['time'];
            $tags = '';
            //多个类型数据组装成字符串
            foreach ($script_data['script_class'] as $k => $v) {
                if (empty($tags)) {
                    $tags = $v['script_setting']['name'];
                } else {
                    $tags .= (',' . $v['script_setting']['name']);
                }
            }
            $post['script_tags'] = $tags;
            $this->model->save($post);
            $Msg_model = app('app\api\model\Msg');
            $content = '您已成功创建关于"'.$script_data['name'].'"的车队';
            if($type == 2){
                //用户创建
                $msg = ['type'=>1,'name'=>'创建车队成功','user_index_id'=>$this->userinfo['id'],'content'=>$content];
                //添加预约量记录
                $ScriptYyLog_model = app('app\admin\model\ScriptYyLog');
                $ScriptYyLog_model->save([
                    'business_id'=>$post['business_id'],
                    'script_id'=>$post['script_id']
                ]);
            }else{
                //门店创建
                $msg = ['type'=>2,'name'=>'创建车队成功','business_id'=>$this->businessinfo['id'],'content'=>$content];
            }
            $Msg_model->save($msg);
            //添加成员数据
            $this->member($this->model->id,$type);
            return datasuccess();
        } else {
            return msgerror('参数缺失');
        }
    }
    //创建车队后，根据类型添加对应的成员数据
    //门店创建车队，会自动随机生成一个虚拟人物成为队长
    protected function member($id,$type)
    {
        $OrderMember_model = app('app\api\model\OrderMember');
        $arr = [
            'order_fleet_id'=>$id,
            'type'=>1
        ];
        if($type == 1){
            //门店
            $VirtualCharacters_model = app('app\api\model\VirtualCharacters');
            $VirtualCharacters_data = $VirtualCharacters_model->select()->toArray();
            $id = [];
            foreach ($VirtualCharacters_data as $v){
                $id[] = $v['id'];
            }
            //rand_arr_from_array 自定义方法随机从数组中获得指定数量的元素
            $member_data = rand_arr_from_array($id, 1);
            $VirtualCharacters_data = $VirtualCharacters_model->where('id',$member_data[0])->find()->toArray();

            $arr['virtual_characters_id'] = $VirtualCharacters_data['id'];
            $arr['user_type'] = 3;
            $arr['name'] = $VirtualCharacters_data['name'];
        }else{
            //用户
            $arr['user_index_id'] = $this->userinfo['id'];
            $arr['user_type'] = 1;
            $arr['cj_status'] = 1;
            $arr['name'] = $this->userinfo['nickname'];
            $arr['tel'] = $this->userinfo['tel'];
        }
        $OrderMember_model->save($arr);
    }
    //车队-详情接口
    public function view()
    {
        if (!input('post.id')) {
            return msgerror('缺少参数id');
        }
        $this->where[] = ['id', '=', input('post.id')];
        $list = $this->model->with($this->with)->where($this->where)->find()->toArray();
        //urladd自定义域名追加方法
        urladd($list);
        $time = strtotime($list['update_time']);
        $list['update_time'] = date('Y-m-d', $time);
        if (!empty($this->with)) {
            foreach ($this->with as $k => $v) {
                if (is_string($v)) {
                    urladd($list[$v]);
                } else {
                    urladd($list[$k]);
                }
            }
        }
        //轮播添加域名前缀
        if (isset($list['script']['images']) && !empty($list['script']['images'])) {
            $images = explode(',', $list['script']['images']);
            foreach ($images as $k => $v) {
                $images[$k] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $v;
            }
            $list['script']['images'] = $images;
        }
        return datasuccess($list);
    }
    //用户端-车队详情
    public function user_view()
    {
        $this->checkLogin();
        $post = param();
        //车队ID
        if(!isset($post['id'])) return msgerror('参数缺失');
        $data = $this->model->where('id',$post['id'])->with($this->with)->find()->toArray();
        $user = app('app\api\model\OrderMember')->where([
            ['user_index_id','=',$this->userinfo['id']],
            ['order_fleet_id','=',$post['id']]
        ])->find();
        $arr['order'] = $data;
        $arr['user'] = $user;
        return datasuccess($arr);
    }
    //用户端-解散车队
    public function js()
    {
        $this->checkLogin();
        $post = param();
        if(!isset($post['id'])) return msgerror('');
        $data = $this->model->where('id',$post['id'])->with(['script'])->find()->toArray();
        if($data['status'] == 1){
            $user = app('app\api\model\OrderMember')->where([
                ['type','=',1],
                ['order_fleet_id','=',$post['id']]
            ])->find()->toArray();
            if($user['user_index_id'] == $this->userinfo['id']){
                $app = Factory::miniProgram($this->yh_easy_config);
                $this->model::update(['id' => $post['id'], 'status' => 5,'content'=>'车队队长解散']);
                app('app\api\model\OrderMember')->where('order_fleet_id', '=', $data['id'])->select()->update(['status' => 2]);
                //发送消息-告诉所有成员解散车队了
                $member_all = app('app\api\model\OrderMember')->where([
                    ['order_fleet_id','=',$data['id']],
                    ['status','=',1],
                    ['user_type','=',1]
                ])->with(['user_index'])->select();
                if(!empty($member_all) && !empty($member_all->toArray()))
                {
                    $member_all = $member_all->toArray();
                    $arr = [];
                    $Msg_model = app('app\api\model\Msg');
                    foreach ($member_all as $k=>$v)
                    {
                        $arr[] = [
                            'type'=>1,
                            'user_index_id'=>$v['user_index_id'],
                            'name'=>'您所在的车队已解散',
                            'content'=>'您所在的关于'.($data['script']['name']??'').'的车队已解散',
                            'no_content'=>'车队队长解散'
                        ];
                        if(!empty($v['user_index']['openid'])){
                            $dy_data = [
                                'template_id' => '1do50m-mPDOQ9Y1__7VULQwb48ttNo1lQWtU_8d0YZQ', // 所需下发的订阅模板id
                                'touser' => $v['user_index']['openid'],     // 接收者（用户）的 openid
                                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                                    'thing1' => [
                                        'value' => $data['script']['name'],
                                    ],
                                    'time2' => [
                                        'value' => date('Y-m-d H:i:s'),
                                    ],
                                    'thing3' => [
                                        'value' => '队长解散',
                                    ],
                                ],
                            ];
                            $app->subscribe_message->send($dy_data);
                        }
                    }
                    //消息通知添加
                    $Msg_model->saveAll($arr);
                }
                //微信订阅消息
                return datasuccess([],'解散成功');
            }else{
                return msgerror('只有车队长才能解散车队');
            }
        }else{
            return msgerror('只有待发车的车队可以解散');
        }
    }
    //商户端-解散车队
    public function bus_js()
    {
        $this->businessCheckLogin();
        if (!input('id')) return msgerror('参数缺失');
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        $app = Factory::miniProgram($this->yh_easy_config);
        if ($data['business_id'] == $this->businessinfo['id']) {
            Db::startTrans();
            try {
                $this->model::update(['id' => $data['id'], 'status' => 5,'content'=>(input('content')?:'')]);
                app('app\api\model\OrderMember')->where('order_fleet_id', '=', $data['id'])->select()->update(['status' => 2]);
                //发送消息-告诉所有成员解散车队了
                $member_all = app('app\api\model\OrderMember')->where([
                    ['order_fleet_id','=',$data['id']],
                    ['status','=',1],
                    ['user_type','=',1]
                ])->with(['user_index'])->select();
                if(!empty($member_all) && !empty($member_all->toArray()))
                {
                    $member_all = $member_all->toArray();
                    $arr = [];
                    $Msg_model = app('app\api\model\Msg');
                    foreach ($member_all as $k=>$v)
                    {
                         $arr[] = [
                             'type'=>1,
                             'user_index_id'=>$v['user_index_id'],
                             'name'=>'您所在的车队已解散',
                             'content'=>'您所在的关于'.($data['script']['name']??'').'的车队已解散',
                             'no_content'=>(input('content')?:'')
                         ];
                        if(!empty($v['user_index']['wx_openid'])){
                            $dy_data = [
                                'template_id' => '1do50m-mPDOQ9Y1__7VULQwb48ttNo1lQWtU_8d0YZQ', // 所需下发的订阅模板id
                                'touser' => $v['user_index']['openid'],     // 接收者（用户）的 openid
                                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                                    'thing1' => [
                                        'value' => $data['script']['name'],
                                    ],
                                    'time2' => [
                                        'value' => date('Y-m-d H:i:s'),
                                    ],
                                    'thing3' => [
                                        'value' => '门店操作：'.input('content'),
                                    ],
                                ],
                            ];
                            $app->subscribe_message->send($dy_data);
                        }
                    }
                    //消息通知添加
                    $Msg_model->saveAll($arr);
                }
                //微信订阅消息
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return msgerror($e->getMessage());
            }
            return datasuccess([], '解散成功');
        } else {
            return msgerror('该车队不是该门店的，不能进行解散操作');
        }
    }

    //商家端-确认到店
    public function bus_qr()
    {
        $this->businessCheckLogin();
        if (!input('id')) return msgerror('参数缺失');
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        if ($data['status'] != 2) return msgerror('只有待到店的车队才能确认到店');
        if ($data['business_id'] != $this->businessinfo['id']) return msgerror('操作失败，该车队不是该门店所属');
        $this->model::update(['id' => $data['id'], 'status' => 3]);
        return datasuccess([], '确认到店');
    }

    //商户端-评为MVP
    public function bus_mvp()
    {
        $this->businessCheckLogin();
        if (!input('id') || !input('member_id')) return msgerror('参数缺失');
        $id = input('id');
        $member_id = input('member_id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        if ($data['status'] != 3) return msgerror('只有进行中的车队才能评价MVP');
        if ($data['mvp_status'] != 2) return msgerror('该车队已评定过MVP');
        $OrderMember_model = app('app\api\model\OrderMember');
        $member_data = $OrderMember_model->where('id',$member_id)->with('user_index')->find()->toArray();
        $app = Factory::miniProgram($this->yh_easy_config);
        Db::startTrans();
        try {
            app('app\api\model\OrderMember')->update(['id' => $member_id, 'mvp_status' => 1]);
            $this->model::update(['id' => $id, 'mvp_status' => 1,'status'=>4]);
            //添加积分
            $UserIndexIntegralLog_model = app('app\api\model\UserIndexIntegralLog');
            $Integral_model = app('app\api\model\Integral');
            $Integral_data = $Integral_model->where('id',2)->find()->toArray();
            //添加积分流水
            $UserIndexIntegralLog_model->save([
                'user_index_id'=>$member_data['user_index_id'],
                'business_id'=>$this->businessinfo['id'],
                'integral_id'=>2,
                'num'=>$Integral_data['num']
            ]);
            //更新用户累计积分
            $UserIndex_model = app('app\api\model\UserIndex');
            $user_index_data = $UserIndex_model->where('id',$member_data['user_index_id'])->find()->toArray();
            $UserIndex_model::update(['id'=>$member_data['user_index_id'],'total_integral'=>($user_index_data['total_integral']*1+$Integral_data['num']*1)]);
            //发送微信订阅消息-被评选为MVP通知
            if(!empty($member_data['user_index']['wx_openid'])){
                $dy_data = [
                    'template_id' => 'K7TkHZt5ld3AQcCxpnbU4HX31DC1V_4VWtF1N2IZjNg', // 所需下发的订阅模板id
                    'touser' => $member_data['user_index']['openid'],     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'thing1' => [
                            'value' => $data['script']['name'],
                        ],
                        'time2' => [
                            'value' => date('Y-m-d H:i:s'),
                        ],
                        'thing3' => [
                            'value' => $data['business']['nickname'],
                        ],
                    ],
                ];
                $app->subscribe_message->send($dy_data);
            }
            //添加站内消息
            app('app\api\model\Msg')->save([
                'type'=>1,
                'name'=>'被评为MVP',
                'user_index_id'=>$member_data['user_index_id'],
                'content'=>'您在"'.($data['script']['name']??'').'"的车队中被评为MVP',
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return msgerror($e->getMessage());
        }
        return datasuccess([], '评价成功');
    }
    //商户端-删除预约-软删除
    public function bus_delete()
    {
        $this->businessCheckLogin();
        if (!input('id')) return msgerror('参数缺失');
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        if($data['business_id'] != $this->businessinfo['id']) return msgerror('删除失败，该车队不属于该门店');
        if ($data['status'] != 5) return msgerror('只有解散的车队才能删除预约');
        $this->model::update(['id'=>$id,'is_del'=>1]);//软删除
        return datasuccess([],'删除预约成功');
    }
    
}